#include <iostream>
#include <array>
#include <string>

#include "boost/asio/io_context.hpp"
#include "boost/asio/ip/tcp.hpp"
#include "boost/asio/buffer.hpp"
#include "boost/asio/write.hpp"



using boost::asio::ip::tcp;

const int BUF_SIZE = 1024;

void Session(tcp::socket socket){
    try{
        while(true){
            std::array<char, BUF_SIZE> data;

            boost::system::error_code ec;
            //std::cout<<"here 1"<<std::endl;
            std::size_t length = socket.read_some(boost::asio::buffer(data), ec);
            std::cout<<"here 2"<<std::endl;
            std::cout<<length;

            if(ec == boost::asio::error::eof){
                std::cout<<"Connection closed cleanly by peer."<<std::endl;
                break;
            }else if(ec){
                throw boost::system::system_error(ec);
            }

            boost::asio::write(socket, boost::asio::buffer(data, length));
        }
    }catch(const std::exception& e){
        std::cerr<<"Exception: "<<e.what()<<std::endl;
    }
}

int main(int argc, char** argv){
    if(argc != 2){
        std::cerr<<"Usage: "<<argv[0]<<"<port>"<<std::endl;
        return 1;
    }

    unsigned short port = std::atoi(argv[1]);

    boost::asio::io_context io_context;

    tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), port));

    try{
        while(true){
            Session(acceptor.accept());
        }
    }catch(const std::exception& e){
        std::cerr<<e.what()<<std::endl;
    }
    return 0;
}
